﻿using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.TestCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Test
{
    public partial class ProductSelectForm : Form
    {
        private ApiClient _apiClient;
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private readonly Action<Sales_TicketDtos> _onSelected;

        public ProductSelectForm()
        {
            InitializeComponent();
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
            this.dgvpurproduct.CellDoubleClick += dgvpurproduct_CellDoubleClick;
            Search();
        }

        public ProductSelectForm(Action<Sales_TicketDtos> onSelected) : this()
        {
            _onSelected = onSelected;
        }

        /// <summary>
        /// 获取销售单中的产品信息
        /// </summary>
        private async void Search()
        {
            var parameters = new Dictionary<string, string>
            {
                    { "pageindex", PageIndex.ToString() },
                    { "pagesize", PageSize.ToString() },
                    { "product_NameOrNumber",this.textProductName.Text},
                    { "finished_Type", this.cboproductType.Text },
                    { "unit", this.cboUnit.Text }

            };

            var response = await _apiClient.GetAsync<TestApiResult<List<Sales_TicketDtos>>>(
                    endpoint: "api/Read/GetSalesProduct",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 将数据绑定到 DataGridView
                dgvpurproduct.DataSource = response.pageDatas;
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }
        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            textProductName.Text = string.Empty;
            cboproductType.Text = string.Empty;
            cboUnit.Text = string.Empty;
            Search();
        }

        private void dgvpurproduct_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            var row = dgvpurproduct.Rows[e.RowIndex];
            var item = row.DataBoundItem as Sales_TicketDtos;
            if (item != null)
            {
                _onSelected?.Invoke(item);
                this.Close();
            }
        }
    }
}
